﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AteneoLibriBusinessLogic.Entities;
using AteneoLibriBusinessLogic.MyException;

namespace AteneoLibriBusinessLogic.DAL
{
    public class NationFacade
    {

        AteneoLibriEntityFramework.AteneoLibriEntities db = new AteneoLibriEntityFramework.AteneoLibriEntities();

        public List<Nation> getNations()
        {
            List<Nation> nations = new List<Nation>();
            List<AteneoLibriEntityFramework.Nation> nationsEF = db.Nations.ToList();

            foreach (var item in nationsEF)
            {
                var nation = TOA.NationAssembler.Assembler(item);
                nations.Add(nation);
            }

            return nations;
        }


        public Nation getNation(Guid nationId)
        {
            Nation nation = getNations().Where(x => x.IdNation == nationId).FirstOrDefault();
            return nation;
        }

        public bool insertNation(Nation nation)
        {
            bool result = false;
            try
            {
                AteneoLibriEntityFramework.Nation nationEF = TOA.NationAssembler.DeAssembler(nation);
                db.Nations.AddObject(nationEF);
                db.SaveChanges();

                result = true;
            }
            catch (Exception ex)
            {
                throw new DALException(ex.Message, ex);
            }
            return result;
        }

        public bool updateNation(Nation nation)
        {
            bool result = false;
            try
            {
                AteneoLibriEntityFramework.Nation nationEF = db.Nations.Where(x => x.IdNation == nation.IdNation).FirstOrDefault();
                //saleEF = TOA.SaleAssembler.DeAssembler(sale);
                TOA.NationAssembler.WriteToEntity(nationEF, nation);

                db.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
                result = true;
            }
            catch (Exception ex)
            {
                throw new DALException(ex.Message, ex);
            }

            return result;
        }


        public bool deleteNation(Nation nation)
        {
            bool result = false;
            try
            {
                AteneoLibriEntityFramework.Nation nationEF = db.Nations.Where(x => x.IdNation == nation.IdNation).FirstOrDefault();
                db.DeleteObject(nationEF);
                db.SaveChanges();

                result = true;
            }
            catch (Exception ex)
            {
                throw new DALException(ex.Message, ex);
            }

            return result;
        }
    }
}
